package com.youlu.campus.admin.community.controller;

import com.youlu.campus.admin.utils.AuthUtils;
import com.youlu.campus.admin.utils.ExcelUtils;
import com.youlu.campus.admin.utils.excel.ExcelListener;
import com.youlu.campus.common.base.RestResult;
import com.youlu.campus.common.base.RestResultBuilder;
import com.youlu.campus.common.utils.RedisKeyUtil;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.ActivityUserRecord;
import com.youlu.campus.entity.SystemOptLog;
import com.youlu.campus.entity.VO.req.ImportActivityPlatformVO;
import com.youlu.campus.entity.VO.req.ImportUserActivityQVO;
import com.youlu.campus.entity.VO.req.ImportUserCertificateVO;
import com.youlu.campus.entity.VO.req.PlatformActivityQueryVO;
import com.youlu.campus.entity.ca.dto.CaRecordDeleteDTO;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.activity.impl.PlatformOtherActivityService;
import com.youlu.campus.service.system.SystemOptLogService;
import com.yuelin.infrastructure.quantum.common.QResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class ActivityPlatformController {

    @Autowired
    private PlatformOtherActivityService platformOtherActivityService;
    @Autowired
    private SystemOptLogService systemOptLogService;
    @Autowired
    private ActivityService activityService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/activity-platform/import")
    public RestResult importActivityPlatform(@RequestParam("file") MultipartFile file, @RequestParam("appId") String appId, @RequestParam("activityId") String activityId, @RequestParam("taskBizType") String taskBizType) {
        String key = RedisKeyUtil.getActivityPlatformImportLock();
        Boolean b = redisTemplate.opsForValue().setIfAbsent(key, "1", 30, TimeUnit.MINUTES);
        if (!b) {
            return RestResultBuilder.builder().failure().message("上一次数据正在导入中,请稍后重试").build();
        }
        long startTime = System.currentTimeMillis();
        try {
            ExcelListener<ImportActivityPlatformVO> objectExcelListener = ExcelUtils.readExcelAndValidate(file, ImportActivityPlatformVO.class);
            if (!objectExcelListener.isSuccess()) {
                return RestResultBuilder.builder().failure().message(objectExcelListener.getErrorMessage()).build();
            }
            if (objectExcelListener.isEmpty()) {
                return RestResultBuilder.builder().failure().message("导入文件为空文件").build();
            }
            List<ImportActivityPlatformVO> dataList = objectExcelListener.getDataList();
            platformOtherActivityService.otherPlatformActivityImport(dataList, appId, activityId, taskBizType);
        } finally {
            redisTemplate.delete(key);
            log.info("导入数据完成,耗时:{}", System.currentTimeMillis() - startTime);
        }
        return RestResultBuilder.builder().success(true).build();
    }

    @PostMapping("/activity-platform/contribution-value")
    public RestResult importExcel(@RequestParam("file") MultipartFile file, @RequestParam("activityId") String activityId) {
        List<ImportUserActivityQVO> excelDataList = ExcelUtils.readExcel(file, ImportUserActivityQVO.class);
        if (CollectionUtils.isEmpty(excelDataList)) {
            return RestResultBuilder.builder().failure("导入文件错误").build();
        }
        platformOtherActivityService.updateUserContributionValue(excelDataList, activityId);
        return RestResultBuilder.builder().success(true).build();
    }


    @PostMapping("/activity-platform/certificate/import")
    public RestResult importUserCertificate(@RequestParam("file") MultipartFile file) {
        List<ImportUserCertificateVO> excelDataList = ExcelUtils.readExcel(file, ImportUserCertificateVO.class);
        if (CollectionUtils.isEmpty(excelDataList)) {
            return RestResultBuilder.builder().failure("导入文件错误").build();
        }
        platformOtherActivityService.importUserCertificate(excelDataList);
        return RestResultBuilder.builder().success(true).build();
    }

    @PostMapping("/activity-platform/list")
    public RestResult list(@RequestBody PlatformActivityQueryVO platformActivityQuery) {
        return RestResultBuilder.builder().success(platformOtherActivityService.list(platformActivityQuery)).build();
    }

    @GetMapping("/activity-platform/detail")
    public RestResult detail(@RequestParam("id") String id) {
        return RestResultBuilder.builder().success(platformOtherActivityService.detail(id)).build();
    }

    @PostMapping("/activity-platform/edit")
    public RestResult edit(@RequestBody ActivityUserRecord activityUserRecord) {
        platformOtherActivityService.edit(activityUserRecord);
        return RestResultBuilder.builder().success(true).build();
    }

    /**
     * 导入批量删除活动收款导入数据
     *
     * @param req
     * @return
     */
    @PostMapping("/activity-platform/delete")
    public QResult batchDelete(@RequestBody @NotNull CaRecordDeleteDTO req) {
        if (StringUtils.isNotBlank(req.getActivityId())) {
            ActivityInfo activityInfo = activityService.findOne(req.getActivityId());
            if (!AuthUtils.getUserId().equals(activityInfo.getCreatorId())) {
                log.error(":>>>  当前操作用户:{},不是活动创建者，不能删除", AuthUtils.getLoginName());
                return QResult.fail("当前操作用户,不是活动创建者");
            }
        }
        this.saveDeleteCaRecordLog(AuthUtils.getLoginName(), "", req.getDesc());
        platformOtherActivityService.batchDelete(req.getActivityId(), req.getTaskBizType(), req.getCaLevel());
        return QResult.success(null);
    }

    /**
     * 查询活动收款导入数据数量
     *
     * @param req
     * @return
     */
    @PostMapping("/activity-platform/count")
    public QResult batchCount(@RequestBody @NotNull CaRecordDeleteDTO req) {
        Long c = platformOtherActivityService.batchCount(req.getActivityId(), req.getTaskBizType(), req.getCaLevel());
        return QResult.success(c);
    }

    private void saveDeleteCaRecordLog(String userLoginName, String ip, String desc) {
        SystemOptLog optlog = new SystemOptLog();
        optlog.setIp(ip);
        optlog.setOptUserName(userLoginName);
        optlog.setOptTime(new Date());
        optlog.setBizType("delete-ca-record");
        optlog.setOptRealName(userLoginName);
        optlog.setSqlDetai("");
        optlog.setDesc("删除导入证书,操作原因" + desc);
        systemOptLogService.create(optlog);

    }


}
